#include"mfbase.h"

MFBase::MFBase() {
	list<Process> queue;
	vector<int> ran;
	int aging_time = 0;
}

MFBase::MFBase(int aging) {
	list<Process> queue;
	vector<int> ran;
	int aging_time = aging;
}

MFBase::~MFBase() {
}

Process MFBase::run_next_process(bool run, int clk) {
	Process result;
	
	if(run) {
		queue.front().run_for(1);
		ran.push_back(queue.front().get_pid());
		if(queue.front().is_done()) {
			result.clone(Process(queue.front()));
			queue.pop_front();
			result.wait_at(clk + 1);
		}
	} else {
		ran.push_back(-1);
	}
	
	return result;
}

void MFBase::print_gantt() {
	int previous = -1;
	
	for(int i = 0; i <= (int)ran.size(); i++) {
		if(i < (int)ran.size()) {
			if(ran[i] != previous) {
				if(previous != -1) {
					cout << " [" << previous << "] " << i;
				}
				previous = ran[i];
			}
		} else if(i != 0 && (ran[i - 1] == previous) && (previous != -1)) {
			cout << " [" << previous << "] " << i;
		} else if(i != 0 && (ran[i - 1] != -1)) {
			cout << " [" << ran[i - 1] << "] " << i;
		}
	}
}

void MFBase::add_process(Process p) {
	queue.push_back(p);
}

bool MFBase::contains(Process p) {
	list<Process>::iterator itr;
	itr = find(queue.begin(), queue.end(), p);
	
	return (p == *itr);
}

bool MFBase::is_empty() {
	return queue.empty();
}

list<Process> MFBase::get_aged_processes(int clk) {
	list<Process> results;
	
	list<Process>::iterator itr;
	for(itr = queue.begin(); itr != queue.end(); itr++) {
		if(itr -> age_up(clk, aging_time)) {
			results.push_back(*itr);
			remove(queue.begin(), queue.end(), *itr);
		}
	}
	
	return results;
}
